package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.PageListUtil;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.ChannelAddDTO;
import org.jsola.hr.dto.ChannelUpdateDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.provider.IRecruitProviderService;
import org.jsola.hr.query.ChannelQuery;
import org.jsola.hr.service.IChannelService;
import org.jsola.hr.vo.ChannelImportExcelVO;
import org.jsola.hr.vo.ChannelListVO;
import org.jsola.hr.vo.ChannelVO;
import org.jsola.hr.vo.HrSiteVO;
import org.jsola.recruit2.entity.BrokerDO;
import org.jsola.salary.query.ChannelFeeSettlementQuery;
import org.jsola.salary.vo.ChannelFeeSum;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 渠道管理
 *
 * @author zhr
 */
@RestController("hrChannelController")
@RequestMapping(HrConstants.API_PATH + "/v1/channels")
public class ChannelController implements IChannelControllerAPI {

    @Autowired
    private IChannelService channelService;
    @Autowired
    private IRecruitProviderService recruitProviderService;


    @Override
    @PostMapping(value = "/feeSum")
    public Result<ChannelFeeSum> feeSum(@Valid @RequestBody ChannelFeeSettlementQuery channelFeeSettlementQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看渠道劳务费结算权限校验

        ChannelFeeSum channelFeeSettlementDOList = channelService.feeSum(channelFeeSettlementQuery, tokenUser);
        return Result.success(channelFeeSettlementDOList);
    }

    @Override
    @GetMapping("/pageChannelList")
    public Result<Page<ChannelListVO>> pageChannelList(@Valid  ChannelQuery channelQuery) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                channelService.pageChannelList(channelQuery, tokenUser)
        );
    }

    @Override
    @PostMapping("/synchronizationBroker")
    public Result<Integer> synchronizationBroker(@RequestBody String[] channelIds) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                channelService.synchronizationBroker(channelIds, tokenUser)
        );
    }

    @Override
    @PostMapping
    public Result<ChannelVO> save(@Valid @RequestBody ChannelAddDTO channelAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增渠道管理权限校验

        return Result.success(
                channelService.save(channelAddDTO, true, tokenUser)
        );
    }

    @Override
    @PostMapping("/importChannel")
    public Result<ChannelImportExcelVO> importChannel(@RequestParam("file") MultipartFile file) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导入解析excel权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                channelService.importChannel(excelFile, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody ChannelUpdateDTO channelUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改渠道管理权限校验

        int count = channelService.update(channelUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{channelId}")
    public Result<Integer> delete(@PathVariable String channelId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除渠道管理权限校验

        int count = channelService.deleteByIds(tokenUser, channelId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] channelIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除渠道管理权限校验

        int count = channelService.deleteByIds(tokenUser, channelIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{channelId}")
    public Result<ChannelVO> findById(@PathVariable String channelId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看渠道管理权限校验

        return Result.success(
                channelService.selectById(channelId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping("/listAllNoSynchronizationBroker")
    public Result<Page<ChannelListVO>> listAllNoSynchronizationBroker(ChannelQuery channelQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看渠道管理权限校验

        List<ChannelListVO> channelListVOList = channelService.select(channelQuery, tokenUser.getSiteId());
        Map<String, ChannelListVO> collect = channelListVOList.stream().collect(Collectors.toMap(ChannelListVO::getPhone, p -> p));
        List<BrokerDO> allBroker = recruitProviderService.getAllBroker(tokenUser);
        for (BrokerDO brokerDO : allBroker) {
            if (collect.containsKey(brokerDO.getPhone())) {
                collect.remove(brokerDO.getPhone());
            }
        }
        List<ChannelListVO> collect1 = new ArrayList<>(collect.values());
        List<ChannelListVO> list = PageListUtil.startPage(collect1, channelQuery.getPageNo(), channelQuery.getPageSize());

        return Result.success(
                new Page<>(list, channelQuery.getPageNo(), channelQuery.getPageSize(), collect1.size())
        );

    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<ChannelListVO>> listAll(@Valid ChannelQuery channelQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看渠道管理权限校验

        List<ChannelListVO> channelListVOList = channelService.select(channelQuery, tokenUser.getSiteId());
//        channelListVOList.forEach(channelListVO ->
//                channelListVO.setNumberPeople(channelService.selectCountByChannelId(channelListVO.getId(), tokenUser)));

        if (channelQuery.getIsNotChannel() != null && channelQuery.getIsNotChannel()) {
            ArrayList<ChannelListVO> channelListVOS = new ArrayList<ChannelListVO>();
            ChannelListVO channelListVO = new ChannelListVO();
            channelListVO.setId("无渠道");
            channelListVO.setName("无渠道");
            channelListVOS.add(channelListVO);
            for (ChannelListVO listVO : channelListVOList) {
                channelListVOS.add(listVO);
            }
            return Result.success(
                    channelListVOS
            );
        } else {
            return Result.success(
                    channelListVOList
            );
        }
    }

    @Override
    @GetMapping(value = "/listSiteAll")
    public Result<List<ChannelListVO>> listSiteAll(ChannelQuery channelQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                channelService.select(channelQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAllForMini")
    public Result<List<ChannelListVO>> listAllForMini(@RequestParam String siteId) {
        ChannelQuery channelQuery = new ChannelQuery();
        List<ChannelListVO> channelListVOList = channelService.select(channelQuery, siteId);
        return Result.success(
                channelListVOList
        );
    }

    @Override
    @GetMapping(value = "/listWithSite")
    public Result<List<ChannelListVO>> listWithSite(ChannelQuery channelQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                channelService.select(channelQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<ChannelListVO>> page(@Valid ChannelQuery channelQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        Page<ChannelListVO> page = channelService.selectPage(channelQuery, tokenUser.getSiteId());
        channelService.selectCountByChannelIdList(page.getEntities(), tokenUser);
        return Result.success(
                page
        );
    }

    @Override
    @GetMapping("/pageAndCompany")
    public Result<Page<ChannelListVO>> pageAndCompany(@Valid ChannelQuery channelQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        Page<ChannelListVO> page = channelService.selectPageAndCompany(channelQuery, tokenUser.getSiteId());
        page.getEntities().forEach(channelListVO ->
                channelListVO.setNumberPeople(channelService.selectCountByChannelId(channelListVO.getId(), tokenUser)));
        return Result.success(
                page
        );
    }

    @Override
    @GetMapping("/selectSiteByUserId")
    public Result<List<HrSiteVO>> selectSiteByUserId() {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                channelService.selectSiteByUserId(tokenUser.getUserId())
        );
    }

    @Override
    @GetMapping("/channelInfoExport")
    public ResponseEntity<Resource> channelInfoExport(@Valid ChannelQuery channelQuery) {
        TokenUser tokenUser = UserContext.getUser();

        // todo 新增员工参保信息表权限校验
        String excelFilePath = channelService.channelInfoExport(channelQuery, tokenUser);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

}

